import os
import sys
import traceback
import datetime
import xlrd1
import PyRSS2Gen
import urllib2
import urllib
import l_time
from ooxml.spreadsheet import Spreadsheet

ltime = l_time.l_time()
home_path = os.getcwd()
try:
    import error
except ImportError, e:
    import sys
    import os
    if 'error' in os.getcwd():
        #print os.getcwd()
        sys.path.append(os.getcwd)
        #print sys.path
        import error
    else:
        #print os.getcwd()
        sys.path.append(os.getcwd)
        os.chdir('..\\')
        x = os.getcwd()
        #print os.getcwd()
        #print sys.path
        sys.path.append(x)
        import error
        import config

class convert(object):
    def __init__(self,parent=None):
        super(convert, self).__init__()
        
    def win_error(self, data, addinfo=None):
        print "Error = ",data
        error_win = error.elogin(data[0],data[1],self,addinfo)
        #win_about.setData("Just me and todut kevin raja unying and pesek")
        #win_about.setInfo("error")
        error_win.show()
        del(error_win)
        
    def format_ext(self,extention):
        ext  = []
        s01  = str(extention).upper()
        s02  = str(extention).title()
        s03  = str(extention).lower()
        for i in range(1,len(extention)):
            s = str(extention).replace(extention[i],extention[i].upper())
            ext.append(s)
        for j in range(0,len(extention)):
            u = str(s01).replace(s01[j],s01[j].lower())
            ext.append(u)
        ext.append(s01)
        ext.append(s02)
        ext.append(s03)
        return ext
        
    def check_url(self, url):
        try:
            a = urllib2.Request(url)
            return True
        except:
            return False

    def Xls_to_Rss(self,data,num_index=0,tt=None,ln=None,desc=None,lastbuild=None,generator=None):
        try:
            if os.path.splitext(data)[1] == '' or os.path.splitext(data)[1] == None:
                self.win_error(['error','format file anda salah !'])
                return
            if tt == None:
                tt = os.path.basename(data)
            if ln == None:
                ln = 'http://www.etik.net/soal/'
            if desc == None:
                desc = data
            if generator == None:
                generator = data
            if lastbuild == None:
                lastbuild = ltime.getnow()
            
            header_xml = """<?xml version="1.0" encoding="iso-8859-1"?>"""
            start_element = """<rss version="2.0">"""
            start_channel = """ <channel>"""
            end_channel = """ </channel>"""
            end_element = """</rss>"""
            start_item = """  <item>"""
            end_item = """  </item>"""
            start_title = """  <title>"""
            end_title = """  </title>"""
            start_link = """  <link>"""
            end_link = """  </link>"""
            start_desc = """  <description>"""
            end_desc = """  </description>"""
            start_builddate = """  <lastBuildDate>"""
            end_builddate = """  </lastBuildDate>"""
            start_generator = """  <generator>"""
            end_generator = """  </generator>"""
            start_doc = """  <doc>"""
            end_doc = """  </doc>"""
            start_guid = """  <guid isPermaLink="true">"""
            end_guid = """  </guid>"""
            start_pubdate = """  <pubDate>"""
            end_pubdate = """  </pubDate>"""
            
            book = xlrd1.open_workbook(data)
            name_sheet = book.sheet_names()
            sh = book.sheet_by_index(num_index)
            num_soal = len(sh.col_values(2,1))
            soal = sh.col_values(2,1)
            print name_sheet
            print '_'*100
            
            rss = header_xml + "\n" + start_element + "\n" + start_channel + "\n" + start_title + str(tt) + end_title + "\n" + start_link +  str(ln) + end_link + "\n" + start_desc + str(desc) + end_desc + "\n" + start_builddate + str(lastbuild) + end_builddate + "\n" + start_generator + str(generator) + end_generator + "\n" + start_doc + "jumlah soal : " + str(num_soal) + end_doc + "\n" 
            rss_end = end_channel + "\n" + end_element
            rss_item = ""
               
            for s in (soal):
                if s != '' :#and s != '' and s != None:
                    n = soal.index(s)
                    opt = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']
                    jawaban_pilihan = sh.row_values(int(n)+1,3)
                    jawaban_opt = []
                    try:
                        for f in range(len(opt)):
                            if jawaban_pilihan[f] != '':
                                x = opt[f] + ". " + jawaban_pilihan[f]
                            else:
                                pass
                            jawaban_opt.append(x)
                    except:
                        pass
                    jawaban_opt[-1] = str(str(jawaban_opt[-1]).split(".")[1]).strip()
                    type_soal = sh.col_values(1,1)[int(n)]
                    #h = "#".join(jawaban_pilihan)
                    h = " #".join(jawaban_opt)
                    #print "Soal = ", s
                    #print "Type Soal = ",type_soal[int(n)]
                    #print "Jawaban = ", str(jawaban_pilihan )
                    #print h
                    pubTime = ltime.gettime_rss()
                    
                    rss_item_add = start_item + "\n" + start_title + str(s) + end_title + "\n" + \
                        start_link + str(type_soal) + end_link + "\n" + \
                        start_desc + str(h) + end_desc + "\n" + \
                        start_guid + str(ln) + end_guid + "\n" + \
                        start_pubdate + str(pubTime) + end_pubdate + "\n" + end_item + "\n"
                    rss_item = rss_item + rss_item_add
            
            rss_final = rss + rss_item + rss_end
            print "rss = ", rss_final
            os.chdir(home_path)
            file_rss = open(os.path.join(config.this_temp,'soal.rss'), 'w')
            file_rss.write(rss_final)
            file_rss.close()
            
        except:
            tr = traceback.format_exc()
            print "ERROR = ", tr
            e = (sys.exc_type, str(sys.exc_value) + "\n" + "-"*51 + str(tr))
            self.win_error(e)
        
    def Xlsx_to_Rss(self,data,num_index=0,tt=None,ln=None,desc=None,lastbuild=None,generator=None):
        try:
            if os.path.splitext(data)[1] == '' or os.path.splitext(data)[1] == None:
                self.win_error(['error','format file anda salah !'])
                return
            if tt == None:
                tt = os.path.basename(data)
            if ln == None:
                ln = 'http://www.etik.net/soal/'
            if desc == None:
                desc = data
            if generator == None:
                generator = data
            if lastbuild == None:
                lastbuild = ltime.getnow()
            
            header_xml = """<?xml version="1.0" encoding="iso-8859-1"?>"""
            start_element = """<rss version="2.0">"""
            start_channel = """ <channel>"""
            end_channel = """ </channel>"""
            end_element = """</rss>"""
            start_item = """  <item>"""
            end_item = """  </item>"""
            start_title = """  <title>"""
            end_title = """  </title>"""
            start_link = """  <link>"""
            end_link = """  </link>"""
            start_desc = """  <description>"""
            end_desc = """  </description>"""
            start_builddate = """  <lastBuildDate>"""
            end_builddate = """  </lastBuildDate>"""
            start_generator = """  <generator>"""
            end_generator = """  </generator>"""
            start_doc = """  <doc>"""
            end_doc = """  </doc>"""
            start_guid = """  <guid isPermaLink="true">"""
            end_guid = """  </guid>"""
            start_pubdate = """  <pubDate>"""
            end_pubdate = """  </pubDate>"""
            
            #book = xlrd1.open_workbook(data)
            book = Spreadsheet(data)
            #name_sheet = book.sheet_names()
            name_sheet = book.sheet_names
            sh = book.sheet(1)
            row1 = sh.row(1)
            print "row1 = ", row1.cell(3).value
            print sh.cell(2,3).value
            soal = []
            #for i in range(2,
            
            #sh = name_sheet[num_index]
            #num_soal = len(sh.col_values(2,1))
            #num_soal = len(sh.cell(2,1).value)
            #soal = sh.col_values(2,1)
            #print name_sheet
            print '_'*100
            """   
            rss = header_xml + "\n" + start_element + "\n" + start_channel + "\n" + start_title + str(tt) + end_title + "\n" + start_link +  str(ln) + end_link + "\n" + start_desc + str(desc) + end_desc + "\n" + start_builddate + str(lastbuild) + end_builddate + "\n" + start_generator + str(generator) + end_generator + "\n" + start_doc + "jumlah soal : " + str(num_soal) + end_doc + "\n" 
            rss_end = end_channel + "\n" + end_element
            rss_item = ""
            
            for s in (soal):
                if s != '' :#and s != '' and s != None:
                    n = soal.index(s)
                    opt = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']
                    jawaban_pilihan = sh.row_values(int(n)+1,3)
                    jawaban_opt = []
                    try:
                        for f in range(len(opt)):
                            if jawaban_pilihan[f] != '':
                                x = opt[f] + ". " + jawaban_pilihan[f]
                            else:
                                pass
                            jawaban_opt.append(x)
                    except:
                        pass
                    jawaban_opt[-1] = str(str(jawaban_opt[-1]).split(".")[1]).strip()
                    type_soal = sh.col_values(1,1)[int(n)]
                    #h = "#".join(jawaban_pilihan)
                    h = " #".join(jawaban_opt)
                    #print "Soal = ", s
                    #print "Type Soal = ",type_soal[int(n)]
                    #print "Jawaban = ", str(jawaban_pilihan )
                    #print h
                    pubTime = ltime.gettime_rss()
                    
                    rss_item_add = start_item + "\n" + start_title + str(s) + end_title + "\n" + \
                        start_link + str(type_soal) + end_link + "\n" + \
                        start_desc + str(h) + end_desc + "\n" + \
                        start_guid + str(ln) + end_guid + "\n" + \
                        start_pubdate + str(pubTime) + end_pubdate + "\n" + end_item + "\n"
                    rss_item = rss_item + rss_item_add
            
            rss_final = rss + rss_item + rss_end
            print "rss = ", rss_final
            os.chdir(home_path)
            file_rss = open(os.path.join(config.this_temp,'soal.rss'), 'w')
            file_rss.write(rss_final)
            file_rss.close()
        """    
        except:
            tr = traceback.format_exc()
            print "ERROR = ", tr
            e = (sys.exc_type, str(sys.exc_value) + "\n" + "-"*51 + str(tr))
            self.win_error(e)

    def Rss_to_Xls(self,pathfile):
        """
        pathfile is url or path file
        """
        if os.path.isfile(pathfile) == True:
            pass
        else:
            if self.check_url(pathfile) == True:
                pass
            else:
                pass
    def Xml_to_Rss(self, data):
        pass

    def Web_to_Rss(self, data):
        pass

    def _toRss(self,data,num_index=0,tt=None,ln=None,desc=None,lastbuild=None,generator=None):
        try:
            if len(data) > 1 or data == None:
                self.win_error(['error','data tidak ditemukan !'])
                return
            if tt == None:
                tt = os.path.basename(data)
            if ln == None:
                ln = 'http://www.etik.net/soal/'
            if desc == None:
                desc = data
            if generator == None:
                generator = data
            if lastbuild == None:
                lastbuild = ltime.getnow()
            
            header_xml = """<?xml version="1.0" encoding="iso-8859-1"?>"""
            start_element = """<rss version="2.0">"""
            start_channel = """ <channel>"""
            end_channel = """ </channel>"""
            end_element = """</rss>"""
            start_item = """  <item>"""
            end_item = """  </item>"""
            start_title = """  <title>"""
            end_title = """  </title>"""
            start_link = """  <link>"""
            end_link = """  </link>"""
            start_desc = """  <description>"""
            end_desc = """  </description>"""
            start_builddate = """  <lastBuildDate>"""
            end_builddate = """  </lastBuildDate>"""
            start_generator = """  <generator>"""
            end_generator = """  </generator>"""
            start_doc = """  <doc>"""
            end_doc = """  </doc>"""
            start_guid = """  <guid isPermaLink="true">"""
            end_guid = """  </guid>"""
            start_pubdate = """  <pubDate>"""
            end_pubdate = """  </pubDate>"""
            
            rss = header_xml + "\n" + start_element + "\n" + start_channel + "\n" + start_title + str(tt) + end_title + "\n" + start_link +  str(ln) + end_link + "\n" + start_desc + str(desc) + end_desc + "\n" + start_builddate + str(lastbuild) + end_builddate + "\n" + start_generator + str(generator) + end_generator + "\n" + start_doc + "jumlah soal : " + str(num_soal) + end_doc + "\n" 
            rss_end = end_channel + "\n" + end_element
            rss_item = ""
            jawaban_opt = data[-1]
            h = " #".join(jawaban_opt)
            pubTime = ltime.gettime_rss()
            
            rss_item_add = start_item + "\n" + start_title + str(s) + end_title + "\n" + \
                        start_link + str(type_soal) + end_link + "\n" + \
                        start_desc + str(h) + end_desc + "\n" + \
                        start_guid + str(ln) + end_guid + "\n" + \
                        start_pubdate + str(pubTime) + end_pubdate + "\n" + end_item + "\n"
            rss_item = rss_item + rss_item_add
            
            rss_final = rss + rss_item + rss_end
            print "rss = ", rss_final
            os.chdir(home_path)
            file_rss = open(os.path.join(config.this_temp,'soal.rss'), 'w')
            file_rss.write(rss_final)
            file_rss.close()
            
        except:
            tr = traceback.format_exc()
            print "ERROR = ", tr
            e = (sys.exc_type, str(sys.exc_value) + "\n" + "-"*51 + str(tr))
            self.win_error(e)

    def _toXml(self, data):
        pass

    def _toXls(self, data):
        pass
    
#FOR TEST Only :
def main():
    myapp = convert()
    #myapp.Xlsx_to_Rss(r'c:\TEMP\me\test.xlsx')
    #myapp.Xlsx_to_Rss(r'c:\PROJECT_TEMP\evaluasiTIK-Python\system\library\test.xlsx')
    myapp.Xls_to_Rss(r'c:\PROJECT_TEMP\evaluasiTIK-Python\system\library\test.xls')
    
if __name__ == '__main__':
    main()